<template>
  <div>
    <el-card>
      <el-button type="primary" icon="Plus" @click="addTrademark" v-permission="`btn.Trademark.add`">
        添加品牌
      </el-button>
      <el-table style="margin: 10px 0" :border="true" :data="trademarkList">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
              v-permission="`btn.Trademark.update`"
            />
            <el-popconfirm
              :title="`您确定要删除${row.tmName}?`"
              width="250px"
              @confirm="removeTradeMark(row.id)"

            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete" v-permission="`btn.Trademark.remove`" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[2, 3, 4, 5]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="changeSize"
        @current-change="getTrademarkList"
      />
    </el-card>
    <el-dialog
      v-model="dialogTableVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      @close="dialogClose"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  reqTrademarkList,
  reqAddOrUpdateTrademark,
  reqDeleteTradeMark,
} from '@/api/product/trademark/index'
import { ElMessage } from 'element-plus'
import type {
  Records,
  TradeMarkResponse,
  Trademark,
} from '@/api/product/trademark/type'
import type { UploadProps } from 'element-plus'
let pageNo = ref<number>(1)
let limit = ref<number>(3)
let trademarkList = ref<Records>([])
let total = ref<number>(0)
let dialogTableVisible = ref<boolean>(false)
let trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})
const ruleFormRef = ref<FormInstance>()
const validateTmName = (_rule: any, value: any, callback: any) => {
  if (value.length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称必须大于等于2位'))
  }
}
const validateLogoUrl = (_rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('务必上传LOGO图片！'))
  }
}
const rules = reactive<FormRules<Trademark>>({
  tmName: [{ required: true, trigger: 'blur', validator: validateTmName }],
  logoUrl: [{ required: true, validator: validateLogoUrl }],
})

onMounted(() => {
  getTrademarkList()
})
const getTrademarkList = async (pager = 1) => {
  pageNo.value = pager
  reqTrademarkList(pageNo.value, limit.value).then((res: TradeMarkResponse) => {
    if (res.code == 200) {
      trademarkList.value = res.data.records
      total.value = res.data.total
    }
  })
}
const removeTradeMark = (id: number) => {
  reqDeleteTradeMark(id).then((res: any) => {
    if (res.code == 200) {
      ElMessage({ type: 'success', message: '删除品牌成功！' })
      getTrademarkList(
        trademarkList.value.length > 1 ? pageNo.value : pageNo.value - 1,
      )
    } else {
      ElMessage({ type: 'error', message: '删除品牌失败！' })
    }
  })
}
// const chnageCurrent = (currentPage)=>{
//   getTrademarkList(currentPage)
// }
const changeSize = () => {
  getTrademarkList()
}
const addTrademark = () => {
  trademarkParams.id = undefined
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  dialogTableVisible.value = true
}
const updateTrademark = (row: any) => {
  Object.assign(trademarkParams, row)
  dialogTableVisible.value = true
}
const dialogClose = () => {
  ruleFormRef.value?.resetFields()
}
const cancel = () => {
  dialogTableVisible.value = false
}
const confirm = () => {
  ruleFormRef.value
    ?.validate()
    .then(() => {
      reqAddOrUpdateTrademark(trademarkParams).then((res: any) => {
        if (res.code == '200') {
          ElMessage({
            type: 'success',
            message: `${trademarkParams.id ? '修改品牌成功' : '添加品牌成功'}`,
          })
          dialogTableVisible.value = false
          getTrademarkList(trademarkParams.id ? pageNo.value : 1)
        } else {
          ElMessage({
            type: 'error',
            message: `${trademarkParams.id ? '修改品牌失败' : '添加品牌失败'}`,
          })
          dialogTableVisible.value = false
        }
      })
    })
    .catch(() => {
      console.log('校验规则')
    })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 > 4) {
      ElMessage({
        type: 'error',
        message: '上传文件大小应小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必是PNG|JPG|GIF',
    })
    return false
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkParams.logoUrl = response.data
  ruleFormRef.value?.clearValidate('logoUrl')
}
</script>
<script lang="ts">
export default {
  name: 'Trademark',
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
